<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="auto">
      <el-form-item label="计划编号" prop="planNo">
        <el-input v-model="queryParams.planNo" placeholder="请输入计划编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车间" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptList" :normalizer="normalizer" placeholder="选择所属车间"
          style="width: 200px" />
      </el-form-item>
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编码" prop="productCode">
        <el-input v-model="queryParams.productCode" placeholder="请输入产品编码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工艺路线名称" prop="processRouteName">
        <el-input v-model="queryParams.processRouteName" placeholder="请输入工艺路线名称" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工艺路线类型" prop="routeType">
        <el-select v-model="queryParams.routeType" placeholder="请选择工艺路线类型" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.ROUTE_TYPE)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PLAN_STATUS)" :key="dict.value" :label="dict.label"
            :value="parseInt(dict.value)" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openForm(undefined)"
          v-hasPermi="['production:plan:create']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          :loading="exportLoading" v-hasPermi="['production:plan:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch" v-hasPermi="['production:plan:delete']">
          批量删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="计划编号" align="center" prop="planNo" width="200" />
      <el-table-column label="生产订单号" align="center" prop="extCode" width="200" />
      <el-table-column label="车间名称" align="center" prop="deptName" width="120" show-overflow-toolti />
      <el-table-column label="产品名称" align="center" prop="productName" width="200" show-overflow-tooltip />
      <el-table-column label="产品编码" align="center" prop="productCode" width="200" show-overflow-tooltip />
      <el-table-column label="工艺路线名称" align="center" prop="processRouteName" width="200" show-overflow-tooltip />
      <el-table-column label="工艺路线类型" align="center" prop="routeTypeName" width="200" show-overflow-tooltip />
      <el-table-column label="计划开始时间" align="center" prop="planBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束时间" align="center" prop="planEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.planEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际开始时间" align="center" prop="actualBeginTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualBeginTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="实际结束时间" align="center" prop="actualEndTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.actualEndTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划数量" align="center" prop="planQuantity" />
      <el-table-column label="已完成数量" align="center" prop="completeQuantity" width="100" />

      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" fixed="right">
        <template v-slot="scope">
          <span>{{ getDictDataLabel(DICT_TYPE.PLAN_STATUS, scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250" fixed="right">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-receiving" @click="doRequisition(scope.row)"
            :disabled="scope.row.status == 3" v-hasPermi="['production:plan:update']">生产领料
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-files" @click="handleDispatchWork(scope.row.id)"
            v-hasPermi="['production:plan:update']" :disabled="scope.row.status != 0">派工
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openForm(scope.row.id)"
            :disabled="scope.row.status != 0" v-hasPermi="['production:plan:update']">配置工艺
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['production:plan:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 对话框(添加 / 修改) -->
    <PlanForm ref="formRef" @success="getList" />
    <!-- 订单申请表单 -->
    <OrderForm ref="orderFormRef" />
  </div>
</template>

<script>
import * as PlanApi from '@/api/production/plan';
import * as ProductBomApi from '@/api/basic/productbom/index.js';
import * as WorkOrderApi from '@/api/production/workorder';
import PlanForm from './PlanForm.vue';
import OrderForm from '@/views/warehouse/orderRequisition/OrderForm.vue';
import { listDept } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";


export default {
  name: "Plan",
  components: {
    PlanForm,
    OrderForm,
    Treeselect
  },
  data() {
    return {
      deptList: [],

      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产计划列表
      list: [],
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 选中行
      currentRow: {},
      checkedIds: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        planNo: null,
        deptId: null,
        deptName: null,
        productId: null,
        productName: null,
        productCode: null,
        processRouteId: null,
        processRouteName: null,
        routeType: null,
        routeTypeName: null,
        planBeginTime: [],
        planEndTime: [],
        actualBeginTime: [],
        actualEndTime: [],
        status: null,
        createTime: [],
      },
    };
  },
  created() {
    this.getList();
    this.getOptions();
  },
  methods: {
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      // 关键：如果不是第三级节点，则禁用
      return {
        id: node.id,
        label: node.name,
        children: node.children, // 必须包含 children
      };
    },
    getOptions() {
      listDept().then(response => {
        this.deptList = this.handleTree(response.data, "id")[0].children;
      });
    },
    /** 查询列表 */
    async getList() {
      try {
        this.loading = true;
        const res = await PlanApi.getPlanPage(this.queryParams);
        this.list = res.data.list;
        this.total = res.data.total;
      } finally {
        this.loading = false;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 生产领料
    async doRequisition(e) {
      try {
        // 获取产品BOM信息
        let dataList = []
        if (e.productBomId) {
          const res = await ProductBomApi.getProductBom(e.productBomId);
          dataList = res.data.items || [];
        }


        // 准备物料明细数据
        const materialList = dataList.map(item => ({
          materialId: undefined,
          materialName: item.materialName || '',
          materialCode: item.materialCode || '',
          quantity: e.planQuantity * (item.materialNumber || 1),
          batchNo: '',
          materialOptions: []
        }));

        // 准备默认表单数据
        const defaultFormData = {
          orderType: 1,
          sourceType: 3,
          sourceTypeName: "生产工单",
          businessType: 7,
          businessTypeName: "生产领料",
          sourceNo: e.planNo
        };

        // 打开订单表单并传递数据
        await this.$refs.orderFormRef.open(null, false, materialList, defaultFormData);
      } catch (error) {
        console.error('获取BOM信息失败:', error);
        this.$modal.msgError('获取BOM信息失败');
      }
    },
    /** 添加/修改操作 */
    openForm(id) {
      this.$refs["formRef"].open(id);
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
      const id = row.id;
      await this.$modal.confirm('是否确认删除生产计划编号为"' + id + '"的数据项?')
      try {
        await PlanApi.deletePlan(id);
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    /** 批量删除生产计划 */
    async handleDeleteBatch() {
      await this.$modal.confirm('是否确认删除?')
      try {
        await PlanApi.deletePlanList(this.checkedIds);
        this.checkedIds = [];
        await this.getList();
        this.$modal.msgSuccess("删除成功");
      } catch {
      }
    },
    handleRowCheckboxChange(records) {
      this.checkedIds = records.map((item) => item.id);
    },
    /** 派工按钮操作 - 跳转到派工页面 */
    handleDispatchWork(id) {
      this.$router.push({
        path: '/dispatchWork/index',
        query: { planId: id }
      });
    },
    /** 导出按钮操作 */
    async handleExport() {
      await this.$modal.confirm('是否确认导出所有生产计划数据项?');
      try {
        this.exportLoading = true;
        const data = await PlanApi.exportPlanExcel(this.queryParams);
        this.$download.excel(data, '生产计划.xls');
      } catch {
      } finally {
        this.exportLoading = false;
      }
    },
  }
};
</script>
